
// 获取所有tab按钮和内容区块
const tabButtons = document.querySelectorAll('.tab-item');
const scenes = document.querySelectorAll('.scene');

// 为每个scene定义对应的回调函数
const sceneCallbacks = {
  scene1: () => {
    console.log('显示了消息页面')
  },
  scene2: () => {
    console.log('显示了消息页面');
    // 这里写显示消息页面时想执行的逻辑
  },
  scene3: () => {
    console.log('显示了我的页面');
    // 这里写显示我的页面时想执行的逻辑
  }
};

tabButtons.forEach(button => {
  button.addEventListener('click', () => {
    // 如果点击的按钮已经是激活状态，则不执行后续操作
    if (button.classList.contains('active')) {
      return
    }
    
    const targetSceneId = button.getAttribute('data-scene');

    // 1. 切换按钮激活状态
    tabButtons.forEach(btn => btn.classList.remove('active'));
    button.classList.add('active');

    // 2. 显示对应场景，隐藏其他场景
    scenes.forEach(scene => {
      if (scene.id === targetSceneId) {
        scene.classList.add('active');
      } else {
        scene.classList.remove('active');
      }
    });

    // 3. 调用对应的回调函数
    if (sceneCallbacks[targetSceneId]) {
      sceneCallbacks[targetSceneId]();
    }
  });
});

// 页面加载时自动调用初始激活的场景对应函数
document.addEventListener('DOMContentLoaded', () => {
  const activeButton = document.querySelector('.tab-item.active');
  if (activeButton) {
    const activeSceneId = activeButton.getAttribute('data-scene');
    if (sceneCallbacks[activeSceneId]) {
      sceneCallbacks[activeSceneId]();
    }
  }
});

document.getElementById('create-post').addEventListener('click', () => {
  window.location.href = window.location.origin + "/post.html";
});


// 更新推荐信息
document.addEventListener('DOMContentLoaded', function() {
  // 获取DOM元素
  const postContainer = document.getElementById("posts-container")
  const refreshIndicator = document.getElementById("refresh-indicator")
  const scene1 = document.getElementById('scene1');

  function renderPosts(posts) {
    for(const post of posts) {
      const postCard = document.createElement('div');
      postCard.className = 'post-card';
      postCard.innerHTML = `
        <div class="post-title">${post.title}</div>
        <div class="post-content">${post.body}</div>
        <div class="post-meta">
          <span>作者：${post.author}</span>
          <span>${post.datetime}</span>
        </div>
      `
      postContainer.appendChild(postCard)
    }
  }


  // 下拉刷新功能
  let startY;
  let currentY;

  scene1.addEventListener('touchstart', function(e) {
    startY = e.touches[0].clientY
  });

  scene1.addEventListener('touchmove', function(e) {
    currentY = e.touches[0].clientY;
    const scrollTop = scene1.scrollTop;

    // 如果在顶部且向下拉
    if (scrollTop === 0 && currentY > startY) {
      e.preventDefault();
      const pullDistance = currentY - startY;
      if (pullDistance > 50) {
        refreshIndicator.style.display = 'block';
      }
    }
  })

  scene1.addEventListener('touchend', function() {
    if (refreshIndicator.style.display === 'block') {
      // 刷新数据
      refreshIndicator.textContent = '加载中...';
    }
  })
  
  function fresh_posts() {
    // 渲染帖子函数
    const auth = localStorage.getItem('jwt_token')
    const url = '/api/v1/show_posts'
    limit = 10
    
    const headers = new Headers();
    headers.append('Authorization', `Bearer ${auth}`)

    const requestOptions = {
      method: 'GET',
      headers: headers
    };

    // 如果没有登陆过，那就直接跳转
    if (!auth) {
      window.open('/login.html', '_self')
    }

    fetch(`${url}?limit=${limit}`, requestOptions)
    .then(response => {
      if (!response.ok) {
        if (response.status == 401) {
          alert('请登录')
          window.open('/login.html', '_self')
        } else {
          throw new Error(`获取数据失败，状态码：${response.status}`)
        }
      }
      return response.json()
    })
    .then(data => {
      console.log(data)
      //alert('OK')
      renderPosts(data.posts);
    })
    .catch(error => {
      alert(error)
    })
  }

  fresh_posts()
  
})
